<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../../css/public.css" media="all">
    <style>
        .customization_toolBar {
            border: none;
        }

        .customization_toolBar .toolBar {
            border: none;
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            height: 20px;
            margin: 15px 0px 0px 0px;
        }

        .customization_toolBar .toolBar .left_tool_div {
            flex-basis: 70%;
            height: 100%;
            display: flex;
            flex-direction: row;
            align-items: center;
        }

        .left_tool_div > * + * {
            margin-left: 10px;
        }

        .customization_toolBar .toolBar .right_tool_div {
            flex-basis: 30%;
            height: 100%;
            display: flex;
            flex-direction: row;
            justify-content: flex-end;
            align-items: center
        }

        .right_tool_div > * + * {
            margin-left: 10px;
        }

        .text-show-btn {
            border: none;
            font-size: 14px;
            color: #666666;
        }

        .text-show-btn:hover {
            color: #666666;
        }

        #dataPreviewTable {
            width: 100%;
        }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" lay-filter="searchForm">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">平台ID</label>
                            <div class="layui-input-inline">
                                <input type="text" name="userId" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">关联手机</label>
                            <div class="layui-input-inline">
                                <input type="text" name="phoneNumber" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">性别</label>
                            <div class="layui-input-inline">
                                <select name="sex">
                                    <option value="">不限</option>
                                    <option value="男">男</option>
                                    <option value="女">女
                                    <option>
                                </select>
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">年龄层</label>
                            <div class="layui-input-inline">
                                <select name="ageGroup">
                                    <option value="">全部</option>
                                    <option value="10后">10后</option>
                                    <option value="00后">00后</option>
                                    <option value="90后">90后</option>
                                    <option value="80后">80后</option>
                                    <option value="70后">60后</option>
                                    <option value="60后">60后</option>
                                </select>
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">个人身份</label>
                            <div class="layui-input-inline">
                                <input type="text" name="identityJob" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">注册时间</label>
                            <div class="layui-input-inline">
                                <input type="text" name="dateRange" id="dateRange" class="layui-input"
                                       placeholder="请选择时间区间">
                            </div>
                        </div>

                        <div class="layui-inlin" id="area-picker">
                            <div class="layui-form-label required">所在地区</div>
                            <div class="layui-input-inline" style="width: 200px;">
                                <select name="province" class="province-selector" data-value="" lay-filter="province-1">
                                    <option value="">请选择省</option>
                                </select>
                            </div>
                            <div class="layui-input-inline" style="width: 200px;">
                                <select name="city" class="city-selector" data-value="" lay-filter="city-1">
                                    <option value="">请选择市</option>
                                </select>
                            </div>
                            <div class="layui-input-inline" style="width: 200px;">
                                <select name="county" class="county-selector" data-value="" lay-filter="county-1">
                                    <option value="">请选择区</option>
                                </select>
                            </div>
                        </div>

                        <!--<div class="layui-inline">-->
                        <!--    <label class="layui-form-label">公众号</label>-->
                        <!--    <div class="layui-input-inline">-->
                        <!--        <input type="text" name="subscriptionOpenid" autocomplete="off" class="layui-input">-->
                        <!--    </div>-->
                        <!--</div>-->

                        <div class="layui-inline">
                            <label class="layui-form-label">平台身份</label>
                            <div class="layui-input-inline">
                                <select id="identityEnums" name="identityEnums" lay-filter="orderStatus">
                                    <option value="">全部</option>
                                    <option value="EVALUATOR">测评师</option>
                                    <option value="REGIONAL_SERVICE_PROVIDERS">区域服务商
                                    <option>
                                </select>
                            </div>
                        </div>

                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit
                                    lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <fieldset class="customization_toolBar">
            <div class="toolBar">
                <div class="left_tool_div">
                    <div><label id="dateRangeStr" style="font-weight: bold;font-size: 16px"></label></div>
                    <div>
                        <button class="layui-btn layui-btn-primary layui-btn-sm data-add-btn text-show-btn"
                                onclick="identitySearch('REGIONAL_SERVICE_PROVIDERS')">
                            区域服务商<label id="num_providers" style="color:#ff0004;text-decoration: underline;">(5)</label>
                        </button>
                    </div>
                    <div>
                        <button class="layui-btn layui-btn-primary layui-btn-sm data-add-btn text-show-btn"
                                onclick="identitySearch('EVALUATOR')">
                            玫丽测评师<label id="num_evaluators"
                                        style="color:#ffd200;text-decoration: underline;">(5)</label>
                        </button>
                    </div>
                    <div>
                        <button class="layui-btn layui-btn-primary layui-btn-sm data-add-btn text-show-btn"
                                onclick="identitySearch('ISSUBSCRIBED')">
                            绑定公众号<label id="num_subscribers"
                                        style="color:#00ff00;text-decoration: underline;">(5)</label>
                        </button>
                    </div>
                    <div>
                        <form class="layui-form">
                            <input type="checkbox" lay-skin="primary" lay-filter="showAll"
                                   title="全部">
                        </form>
                    </div>
                    <div>
                        <form class="layui-form">
                            <input type="checkbox" lay-skin="primary" lay-filter="filterUsers"
                                   title="过滤无效用户" checked>
                        </form>
                    </div>
                </div>
                <div class="right_tool_div">
                    <div>
                        <button class="layui-btn layui-btn-sm layui-btn-warm customerExportExcel">
                            导出
                        </button>
                    </div>
                </div>
            </div>
        </fieldset>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>
    </div>
</div>
<script src="../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="../../js/lay-config.js?v=1.0.4" charset="utf-8"></script>
<script src="../../lib/common/common.js" charset="utf-8"></script>
<script src="../../lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
<script src="../../js/lay-module/xm-select-master/dist/xm-select.js" charset="utf-8"></script>
<script>
    let allBtnSelect;
    let allStatistics = true;
    let filterUsers = true;
    let identityEnums = null;
    let isSubscribed = false;
    layui.use(['form', 'table', 'laydate', 'layarea'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            laydate = layui.laydate,
            layarea = layui.layarea;

        layarea.render({
            elem: '#area-picker',
            data: {}
        });

        // 默认时间文本
        let defDateRange = new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000).toLocaleDateString().split('/').map(function (item) {
            return item.padStart(2, '0');
        }).join('-') + " - " + new Date().toLocaleDateString().split('/').map(function (item) {
            return item.padStart(2, '0');
        }).join('-')
        setDateRangeStr(defDateRange)

        //执行一个laydate实例
        laydate.render({
            elem: '#dateRange', //指定元素
            max: 0, // 限制最大值为当前日期
            format: 'yyyy-MM-dd', //日期格式
            type: 'date',
            range: true, //开启范围选择
        });


        table.render({
            elem: '#currentTableId',
            url: '/customer/page/list',
            where: {
                dateRange: getDateRangeJsonStr(),
                allStatistics: allStatistics,
                filterUsers: filterUsers
            },
            method: 'GET',
            contentType: 'application/x-www-form-urlencoded',
            parseData: function (res) { //res 即为原始返回的数据
                // 接下来的分页不需要统计
                allStatistics = false;
                let data = res.data;
                // 处理数据
                let customerTypeQuantity = data.customerTypeQuantity;
                if (customerTypeQuantity) {
                    const myMap = new Map(Object.entries(customerTypeQuantity));
                    // 更新统计数据
                    myMap.forEach((value, key) => {
                        let id = '#' + key
                        $(id).text('(' + value + ')');
                    });
                }
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": data.total, //解析数据长度
                    "data": data.list //解析数据列表
                };
            },
            toolbar: false,
            cols: [[
                {type: "checkbox", fixed: 'left'},
                {
                    field: 'numbering', title: '序号', width: 60, align: 'center', templet: function (d) {
                        return d.LAY_INDEX; //返回序号
                    }
                },
                {field: 'createTime', title: '注册时间', sort: true, align: 'center', width: 120},
                {field: 'userId', title: '平台ID', sort: true, align: 'center', width: 120},
                {field: 'userName', title: '平台昵称', sort: true, align: 'center', width: 120},
                {field: 'phoneNumber', title: '关联手机', sort: true, align: 'center', width: 120},
                {field: 'realName', title: '真实姓名', sort: true, align: 'center', width: 120},
                {field: 'sex', title: '性别', sort: true, align: 'center', width: 80},
                {field: 'ageGroup', title: '年龄层', sort: true, align: 'center', width: 100},
                {
                    field: 'region', title: '所在地区', sort: true, align: 'center', width: 120, templet: function (d) {
                        return d.region + " " + d.address;
                    }
                },
                {field: 'identityJob', title: '个人身份', sort: true, align: 'center', width: 120},
                {field: 'monthlyIncome', title: '月收入', sort: true, align: 'center', width: 120},
                {field: 'platformIdentity', title: '平台身份', sort: true, align: 'center', width: 80},
                {
                    field: 'isSubscribed',
                    title: '公众号',
                    sort: true,
                    align: 'center',
                    width: 100,
                    templet: function (d) {
                        if (d.isSubscribed === '1') {
                            return '<span style="color:#4fc44f;">是</span>'
                        } else {
                            return '<span style="color:#ff0000;">否</span>'
                        }
                    }
                },

            ]],
            limits: [50, 100, 150, 200],
            limit: 50,
            page: true,
            request: {
                pageName: 'pageNum',
                limitName: 'pageSize'
            },
            response: { //定义后端 json 格式，详细参见官方文档
                statusName: 'code', //状态字段名称
                statusCode: '200', //状态字段成功值
                msgName: 'msg', //消息字段
                countName: 'count', //总数字段
                dataName: 'data' //数据字段
            },
        });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            allStatistics = true;
            let dataRangeStr = data.field.dateRange
            if (isNotNull(dataRangeStr)) {
                setDateRangeStr(dataRangeStr)
            }
            loadingTable();
            return false;
        });


        form.on('checkbox(showAll)', function (data) {
            if (data.elem.checked) { //判断复选框是否选中
                $('#dateRange').val("")
                allBtnSelect = true;
                setDateRangeStr("");
            } else {
                allBtnSelect = false;
                setDateRangeStr(defDateRange)
            }
            publicDataRecovery()
            loadingTable();
        });

        form.on('checkbox(filterUsers)', function (data) {
            if (data.elem.checked) { //判断复选框是否选中
                filterUsers = true;
            } else {
                filterUsers = false;
            }
            publicDataRecovery()
            loadingTable();
        });


        // 监听导出按钮
        $('.customerExportExcel').click(function () {
            let checkStatus = table.checkStatus('currentTableId');
            let formDate = form.val('searchForm');
            let region = "";
            if (isNotNull(formDate.province)) {
                // 处理参数
                region = formDate.province;
                if (isNotNull(formDate.city)){
                    region += '-' + formDate.city
                }
                if (isNotNull(formDate.county)){
                    region += '-' + formDate.county
                }
            }
            const requestData = {
                dateRange: getDateRangeJsonStr(),
                allStatistics: allStatistics,
                filterUsers: filterUsers,
                identityEnums: identityEnums ?? formDate.identityEnums,
                userId: formDate.userId,
                subscriptionOpenid: formDate.subscriptionOpenid,
                sex: formDate.sex,
                ageGroup: formDate.ageGroup,
                subscribedWX: isSubscribed,
                phoneNumber: formDate.phoneNumber,
                identityJob: formDate.identityJob,
                region: region,
            }
            let data = {
                batchIds: [],
                batchType: 0,
                queryVO: requestData,
            }
            if (checkStatus.isAll) {
                data.batchType = 1;
            } else {
                let dataList = checkStatus.data;
                if (dataList.length > 0) {
                    let ids = [];
                    dataList.forEach(function (item) {
                        ids.push(item.id)
                    });
                    data.batchIds = ids;
                } else {
                    data.batchType = 1;
                }
            }
            downloadExcel('/customer/export/excel', data, '平台用户信息.xlsx', 'POST')
        });

        // 监听表格 行双击事件
        table.on('rowDouble(currentTableFilter)', function (obj) {
            var index = layer.open({
                title: '用户详情',
                type: 2,
                shade: 0.2,
                maxmin: true,
                shadeClose: true,
                area: ['100%', '100%'],
                content: './info.html?id=' + obj.data.id,
            });
            $(window).on("resize", function () {
                layer.full(index);
            });

        });

    });

    /**
     * 重载表格数据
     */
    function reloadTable() {
        layui.use(['table'], function () {
            let table = layui.table;
            table.reload('currentTableId', {
                url: '/customer/page/list'
            });
        })
    }

    /**
     * 重载表格数据
     */
    function loadingTable() {
        layui.use(['form', 'table', 'jquery'], function () {
            var form = layui.form,
                table = layui.table,
                $ = layui.jquery;
            let formDate = form.val('searchForm');
            let region = "";
            if (isNotNull(formDate.province)) {
                // 处理参数
                region = formDate.province;
                if (isNotNull(formDate.city)){
                    region += '-' + formDate.city
                }
                if (isNotNull(formDate.county)){
                    region += '-' + formDate.county
                }
            }
            const requestData = {
                dateRange: getDateRangeJsonStr(),
                allStatistics: allStatistics,
                filterUsers: filterUsers,
                identityEnums: identityEnums ?? formDate.identityEnums,
                userId: formDate.userId,
                subscriptionOpenid: formDate.subscriptionOpenid,
                sex: formDate.sex,
                ageGroup: formDate.ageGroup,
                subscribedWX: isSubscribed,
                phoneNumber: formDate.phoneNumber,
                identityJob: formDate.identityJob,
                region: region,
            }
            // 处理需要传递的参数
            table.reload('currentTableId', {
                page: {
                    curr: 1
                }
                , where: requestData
            }, 'data');
        })
    }

    function identitySearch(identity) {
        if (identity === 'ISSUBSCRIBED') {
            isSubscribed = true;
            identityEnums = null;
        } else {
            isSubscribed = false;
            identityEnums = identity;
        }
        loadingTable();
    }

    // 设置日期显示的文本内容
    function setDateRangeStr(defDateRange) {
        if (!isNotNull(defDateRange)) {
            $("#dateRangeStr").text('全部用户');
            return;
        }
        const [startDateStr, endDateStr] = defDateRange.split(' - ');
        const startDate = new Date(startDateStr);
        const endDate = new Date(endDateStr);
        // 格式化开始日期和结束日期
        const formattedStartDate = formatDate(startDate);
        const formattedEndDate = formatDate(endDate);// 组合新的日期字符串
        const newDateStr = `${formattedStartDate} - ${formattedEndDate}`;
        $("#dateRangeStr").text(newDateStr);
    }

    // 获取时间查询区间
    function getDateRangeJsonStr() {
        let dateRangeStr = $('#dateRange').val();
        if (!isNotNull(dateRangeStr)) {
            if (allBtnSelect) {
                // 代表全部被选中了
                return '{}';
            } else {
                // 默认7天内
                dateRangeStr = new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000).toLocaleDateString().split('/').map(function (item) {
                    return item.padStart(2, '0');
                }).join('-') + " - " + new Date().toLocaleDateString().split('/').map(function (item) {
                    return item.padStart(2, '0');
                }).join('-')
            }

        }
        let dataRangeList = dateRangeStr.split(` - `)
        let dataRange = {}
        if (dataRangeList.length === 2) {
            dataRange = {
                'startDate': dataRangeList[0],
                'endDate': dataRangeList[1]
            }
        }
        return JSON.stringify(dataRange)
    }

    /**
     * 全局参数恢复默认值
     */
    function publicDataRecovery() {
        allStatistics = true;
        identityEnums = null;
        isSubscribed = false;
    }

</script>

</body>
</html>